// pages/containers_inspection.js
const requests = require("../../../../behaviors/requests")
const baseUrl = "https://logisticsengineering.gree.com/container_manage_api/container_manage/"
var location_data = {}
var responsibility_data = {}
Page({
  behaviors: [requests],
  components: [],
  /**
   * 页面的初始数据
   */
  data: {
    stepper: 1,
    baseUrl: "https://logisticsengineering.gree.com/container_manage_api/container_manage",
    uploader: [],
    files: [],
    statusList: [],
    columns: ["月度检查", "监督反馈"],
    columns2: [
    ],
    columns3: [

    ],
    columns4: [

    ],
    columns5: [
    ],
    showPicker: false,
    showPicker2: false,
    showPicker3: false,
    showPicker4: false,
    showPicker5: false,
    problem_source: "监督反馈",

    problem_count: 1,
    problem_category: "",
    problem_description: "其他",
    location: "",
    responsibility: "",
    problem_append: "",
    res_category: "",
    res_accurate: "",

    is_loading: false,
    show_upload: true,
    submit_btn_disabled: false,
    choose_img_btn_disabled: false,
    problem_type_list: [],
    row_data: {},
    objs: {}
  },

  // 获取配置数据
  getConfigDatas() {
    let url = this.data.baseUrl + "/get_config2"
    let data = {}
    this.post(url, data).then(res => {
      console.log("配置数据", res.data)

      if (res.code == 20000) {
        location_data = res.data.地点
        responsibility_data = res.data.责任单位

        let arr = [
          {
            values: Object.keys(location_data),
            className: 'column1',
          },
          {
            values: Object.keys(location_data[Object.keys(location_data)[0]]),
            className: 'column2',
          },
          {
            values: location_data[Object.keys(location_data)[0]][Object.keys(location_data[Object.keys(location_data)[0]])[0]],
            className: 'column3',
            defaultIndex: 2,
          }
        ]
        let arr2 = [{
          values: Object.keys(responsibility_data),
          className: 'column1',
        },
        {
          values: responsibility_data[Object.keys(responsibility_data)[0]],
          className: 'column2',
          defaultIndex: 2,
        }]

        let arr3 = Object.keys(res.data.问题类别)
        console.log(arr3);
        this.setData({
          columns3: arr3,
          problem_type_list: res.data.问题类别,
          // columns3: res.data.问题类别,
          // columns4: res.data.问题描述,
          columns2: arr,
          columns5: arr2,
        })

        // wx.showToast({
        //     title: res.msg,
        //     icon: 'error'
        // })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let self = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      console.log("传过来的数据", data)
      let arr1 = data.files
      let arr2 = []
      for (let i in arr1) {
        let obj =
        {
          url: baseUrl + "fs_download?file_id=" + arr1[i],
          isImage: true
        }
        arr2.push(obj)
      }
      let obj = {
        problem_count: data.problem_count,
        problem_category: data.problem_category,
        problem_description: data.problem_description,
        location: data.location,
        responsibility: data.responsibility,
        problem_append: data.problem_append,
        res_category: data.res_category,
        res_accurate: data.res_accurate,
        files: data.files
      }

      self.setData({
        row_data: data,
        problem_count: data.problem_count,
        problem_category: data.problem_category,
        problem_description: data.problem_description,
        location: data.location,
        responsibility: data.responsibility,
        problem_append: data.problem_append,
        res_category: data.res_category,
        res_accurate: data.res_accurate,
        uploader: arr2,
        objs: obj



      })


    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getConfigDatas()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  show_problem_source() {
    this.setData({
      showPicker: true
    })
  },
  // 地点
  show_location() {
    console.log("xxx")
    this.setData({
      showPicker2: true
    })
  },
  cancel_location() {
    this.setData({
      showPicker2: false
    })
  },
  onConfirm2(e) {
    console.log(e.detail.value);
    this.setData({
      location: e.detail.value[1] + e.detail.value[2],
      showPicker2: false
    });
  },
  onPicker2Change(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    console.log(value, index);

    const c2 = Object.keys(location_data[value[0]]);
    picker.setColumnValues(1, c2);
    if (index == 0) {
      picker.setColumnValues(2, location_data[value[0]][c2[0]]);
    } else {
      picker.setColumnValues(2, location_data[value[0]][value[1]]);
    }

  },
  // 问题类别
  show_problem_category() {
    this.setData({
      showPicker3: true
    })
  },
  cancel_problem_category() {
    this.setData({
      showPicker3: false
    })
  },
  onConfirm3(e) {
    console.log(e.detail);
    let key = e.detail.value
    let arr2 = this.data.problem_type_list[key]
    this.setData({
      problem_category: e.detail.value,
      columns4: arr2,
      showPicker3: false
    });
  },
  // 责任单位
  show_responsibility() {
    this.setData({
      showPicker5: true
    })
  },
  cancel_responsibility() {
    this.setData({
      showPicker5: false
    })
  },
  onConfirm5(e) {
    this.setData({
      responsibility: e.detail.value[0] + "-" + e.detail.value[1],
      showPicker5: false
    });
  },
  onPicker5Change(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    picker.setColumnValues(1, responsibility_data[value[0]]);
  },
  // 问题描述
  show_problem_description() {
    this.setData({
      showPicker4: true
    })
  },
  cancel_problem_description() {
    this.setData({
      showPicker4: false
    })
  },
  onConfirm4(e) {
    this.setData({
      problem_description: e.detail.value,
      showPicker4: false
    });
  },
  onPicker5Change(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    console.log(index)
    picker.setColumnValues(1, responsibility_data[value[0]]);
  },
  // 照片选取
  try_upload(e) {

    const self = this;
    // 关闭照片选取
    self.setData({
      choose_img_btn_disabled: true
    });
    // 确定还有张图片可以选择
    const count = 3 - this.data.uploader.length;
    wx.chooseMedia({
      count: count,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const myUploadFiles = res.tempFiles.map(tempFile => {
          const tempFilePath = tempFile.tempFilePath;
          return self.myUploadFile(tempFilePath);
        });
        wx.showLoading({
          title: '开始上传。。。',
        })
        Promise.all(myUploadFiles).then(file_ids => {
          wx.hideLoading();
          // 处理UI
          console.log(file_ids);
          const uploader = self.data.uploader;
          const new_uploader = uploader.concat(file_ids.map(file_id => {
            return {
              url: baseUrl + "fs_download?file_id=" + file_id,
              isImage: true
            };
          }));
          self.setData({
            uploader: new_uploader
          })
          if (self.data.uploader.length < 3) {
            self.setData({
              choose_img_btn_disabled: false
            });
          }
          wx.showToast({
            title: '上传成功！',
          });

        }).catch(msg => {
          wx.hideLoading();
          if (self.data.uploader.length < 3) {
            self.setData({
              choose_img_btn_disabled: false
            })
          }
          wx.showToast({
            title: msg,
            icon: "error"
          })
          console.log(msg);
        });
      },
      fail() {
        if (self.data.uploader.length < 3) {
          self.setData({
            choose_img_btn_disabled: false
          })
        }
      }
    })
  },
  myUploadFile(file) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: "https://logisticsengineering.gree.com/container_manage_api/container_manage/fs_upload",
        filePath: file,
        name: 'file',
        formData: {},
        success(res) {
          const result = JSON.parse(res.data);
          console.log(result);
          wx.hideLoading();
          if (result.code == 20000) {
            resolve(result.data.file_id);
          } else {
            reject(msg);
          }

        },
        fail() {
          reject("未知错误446");
        }
      })
    });
  },
  handle_delete(e) {
    const index = e.detail.index;
    const file = this.data.uploader[index];
    const file_id = file.url.split("=")[1];
    const uploader = this.data.uploader;
    const self = this;
    this.post(baseUrl + 'fs_delete', { file_id }).then((res) => {
      const code = res["code"];
      if (code == 20000) {
        uploader.splice(index, 1);
        self.setData({
          choose_img_btn_disabled: false
        })
        console.log("uploader", uploader)
        self.setData({
          uploader
        });
      } else {
        wx.showToast({
          title: result.msg,
          icon: "error"
        })
      }
    }).catch(() => {
      console.log("error");
    })
  },

  onStepperChange(value) {
    this.setData({
      problem_count: value.detail
    });
  },
  onSubmit(e) {
    let res_category1 = this.data.responsibility.split("-")[0]
    let res_accurate1 = this.data.responsibility.split("-")[1]
    // let url = self.data.baseUrl + "/update_problem"
    const row = this.data.row_data
    let args1 = {
      problem_count: this.data.problem_count,
      problem_category: this.data.problem_category,
      problem_description: this.data.problem_description,
      location: this.data.location,
      responsibility: this.data.responsibility,
      problem_append: this.data.problem_append,
      res_category: res_category1,
      res_accurate: res_accurate1,
    }
    let lists = []
    lists.push(args1)
    let data = {
      key: row._id,
      company: row.company,
      status: row.status,
      res_accurate: row.res_accurate,
      submitter: row.submitter,
      action: "举报后，待责任单位确认",
      reason: "",
      args: lists,
      files: [],
    }
    // const data = e.detail.value;
    const uploader = [...this.data.uploader];
    uploader.forEach((element, index) => {
      uploader[index] = element.url.split("=")[1];
    });
    args1.files = uploader;
    // 验证参数是否为空
    const field_table = {
      location: "地点",
      problem_category: "问题类别",
      problem_count: "数量",
      problem_description: "问题描述",
      // problem_source: "问题来源",
      responsibility: "责任单位",
    }
    for (var index in field_table) {
      if (!args1[index] || (index == "files" && args1[index].length == 0)) {
        wx.showToast({
          title: field_table[index] + '不允许为空！',
          icon: "error"
        })
        return false;
      }
    }
    
    if (JSON.stringify(args1) === JSON.stringify(this.data.objs)) {
      wx.showToast({
        title: '请修改后再提交！',
        icon: 'error'
      })
    } else {
      const self = this;
      self.setData({
        submit_btn_disabled: true
      })
      // wx.navigateTo({
      //   url: 'url',
      // })

      wx.showLoading({
        title: '数据上传中。。。',
      })

      this.post(baseUrl + "update_problem", data).then((res) => {
        wx.hideLoading();
        self.setData({
          submit_btn_disabled: false,
        })
        const result = res;
        if (result.code == 20000) {
          wx.showToast({
            title: "提交成功!",
          })
          if (row.flag == "flag1") {
            wx.redirectTo({
              url: '/pages/wuliurongqiguanli/nav_handling/handling',
            })
          } else {
            wx.redirectTo({
              url: '/packageB/pages/package/task_manager/task_manager',
            })
          }



        } else {
          wx.showToast({
            title: result.msg,
            icon: "error"
          })
        }
      }).catch((err) => {
        self.setData({
          submit_btn_disabled: false
        })
        wx.showToast({
          title: err.msg,
          icon: "error"
        })
      })
    }

  },


})